<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 查询用户名区域 -->
      <template #header>
        <el-form
          label-width="80px"
          inline
          size="normal"
          style="margin-top: 20px"
        >
          <el-form-item label="" size="normal">
            <el-input
              placeholder="请输入用户名"
              size="normal"
              v-model="searchKeyword"
            ></el-input>
          </el-form-item>
          <el-form-item label="" size="normal">
            <el-button type="primary" @click="searchUser" icon="el-icon-search"
              >查询</el-button
            >
            <el-button @click="clearSearch">清空</el-button>
          </el-form-item>
        </el-form>
      </template>
      <!-- 添加与删除区域 -->
      <div>
        <el-button type="primary" @click="isShowAddUser" v-has="`btn.User.add`"
          >添加</el-button
        >
        <el-button
          type="danger"
          @click="removeUserList"
          :disabled="!idList.length > 0"
          >批量删除</el-button
        >
      </div>
      <!-- 用户列表表格区 -->
      <el-table
        border
        style="margin-top: 20px"
        :data="userList"
        @select-all="checkAllTable"
        @select="checkedTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column label="角色列表" align="center" prop="roleName" />
        <el-table-column label="创建时间" align="center" prop="gmtCreate" />
        <el-table-column label="更新时间" align="center" prop="gmtModified" />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="info"
              size="small"
              icon="el-icon-user-solid"
              v-has="`btn.User.assgin`"
              @click="setUser(row)"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit-outline"
              v-has="`btn.User.update`"
              @click="upDateUser(row)"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              v-has="'btn.User.remove'"
              @click="removeUser(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px"
        :current-page="pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout=" prev, pager, next, jumper, -> ,sizes, total"
        :total="total"
        @current-change="changePageNo"
        @size-change="changePageSize"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的区域 -->
    <el-dialog title="添加用户" :visible.sync="isShowUser">
      <el-form :model="addUserForm" :rules="rules" ref="addUserRef">
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input
            style="width: 80%"
            v-model="addUserForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="100px">
          <el-input
            size="normal"
            style="width: 80%"
            v-model="addUserForm.nickName"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="100px" prop="password">
          <el-input
            type="password"
            size="normal"
            style="width: 80%"
            v-model="addUserForm.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowUser = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户的区域 -->
    <el-dialog title="修改用户" :visible.sync="isShowUpDataUser">
      <el-form :model="addUserForm" :rules="rules" ref="addUserRef">
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input
            style="width: 80%"
            v-model="addUserForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="100px">
          <el-input
            size="normal"
            style="width: 80%"
            v-model="addUserForm.nickName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowUpDataUser = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 设置角色的区域 -->
    <el-dialog title="设置角色" :visible.sync="isShowSetUser" top="200px">
      <el-form>
        <el-form-item label="用户名" size="normal" label-width="100px">
          <el-input
            style="width: 280px"
            size="normal"
            :disabled="true"
            v-model="userInput"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表" size="normal" label-width="100px">
          <el-checkbox v-model="checkAll" @change="changeAll">全选</el-checkbox>
          <div style="margin: 15px 0"></div>
          <el-checkbox-group v-model="checkedCities" @change="changeCities">
            <el-checkbox
              v-for="item in allRolesList"
              :label="item.id"
              :key="item.id"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowSetUser = false">取 消</el-button>
        <el-button type="primary" @click="saveAssgin">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入请求
import {
  asyncGetUserList,
  asyncAddUser,
  asyncGetAssign,
  asyncDoAssign,
  asyncDeleteUser,
  asyncDeleteUserList,
  asyncUpDateUser,
} from "@/api/acl/user";
// 引入element-ui
import { Message } from "element-ui";
// 引入深拷贝函数
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "User",
  data() {
    return {
      // 当前页
      pageNo: 1,
      // 显示条数
      pageSize: 5,
      // 总条数
      total: 0,
      // 用户列表
      userList: [],
      // 搜索用户的关键字
      searchKeyword: "",
      // 控制添加用户对话框的显示与隐藏
      isShowUser: false,
      // 添加用户的数据
      addUserForm: {
        id: "",
        username: "",
        nickName: "",
        password: "",
      },
      // 添加用户的校验规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },

      // 控制修改用户对话框的显示与隐藏
      isShowUpDataUser: false,
      // 控制设置用户对话框的显示与隐藏
      isShowSetUser: false,
      // 控制用户角色的全选状态
      checkAll: false,
      // 所有的角色列表
      allRolesList: [],
      // 当前角色选中的的列表
      checkedCities: [],
      //当前用户的名字
      userInput: "",
      //分配角色的参数
      assignParams: {
        userId: "",
        roleId: [],
      },
      // 存放用户 id 的数组
      idList: [],
    };
  },
  methods: {
    // 请求用户管理的列表
    async getUserList() {
      try {
        let res = await asyncGetUserList(this.pageNo, this.pageSize);
        // console.log(res);
        this.total = res.data.total;
        this.userList = res.data.items;
      } catch (error) {
        console.log(error);
      }
    },
    // 分页器的回调
    changePageNo(page) {
      this.pageNo = page;
      this.getUserList();
    },
    // 改变一页显示个数的回调
    changePageSize(page) {
      this.pageSize = page;
      this.pageNo = 1;
      this.getUserList();
    },
    // 搜索用户的回调
    async searchUser() {
      try {
        let res = await asyncGetUserList(
          this.pageNo,
          this.pageSize,
          this.searchKeyword
        );
        // console.log(res);
        this.total = res.data.total;
        this.userList = res.data.items;
      } catch (error) {
        console.log(error);
      }
    },
    // 清空用户搜索框的回调
    clearSearch() {
      this.searchKeyword = "";
      this.getUserList();
    },

    // 控制添加用户界面的显示与隐藏
    isShowAddUser() {
      this.isShowUser = true;
      this.addUserForm.username = "";
      this.addUserForm.nickName = "";
      this.addUserForm.password = "";
    },
    //添加用户的回调
    addUser() {
      this.$refs.addUserRef.validate(async (vaild) => {
        if (vaild) {
          try {
            if (this.addUserForm.id) {
              await asyncUpDateUser(this.addUserForm);
            } else {
              await asyncAddUser(this.addUserForm);
            }
            // console.log(res);
            this.isShowUser = false;
            this.isShowUpDataUser = false;
            this.getUserList();
            Message.success(this.addUserForm.id ? "修改成功" : "添加成功");
          } catch (error) {
            Message.success(this.addUserForm.id ? "修改失败" : "添加失败");
            console.log(error);
          }
        } else {
          return false;
        }
      });
    },
    // 点击修改用户的回调
    upDateUser(row) {
      this.isShowUpDataUser = true;
      console.log(row);
      this.addUserForm = cloneDeep(row);
    },
    // 设置用用户的回调
    async setUser(row) {
      // console.log(row);
      this.assignParams.userId = row.id;
      this.isShowSetUser = true;
      this.userInput = row.username;
      try {
        let res = await asyncGetAssign(row.id);
        // console.log(res);
        this.allRolesList = res.data.allRolesList;
        this.checkedCities = res.data.assignRoles.map((item) => item.id);
        // console.log( this.checkedCities,'sssss');
      } catch (error) {
        console.log(error);
      }
    },

    // 改变全选的回调
    changeAll(checked) {
      // console.log(checked, "全选");
      if (checked) {
        this.checkedCities = this.allRolesList.map((item) => item.id);
      } else {
        this.checkedCities = [];
      }
    },
    //多选框变化的逻辑
    changeCities(checked) {
      // console.log(checked, "多选框");
      this.checkAll = checked.length === this.allRolesList.length;
    },
    // 点击分配角色框确定的回调
    async saveAssgin() {
      console.log(this.checkedCities);
      this.assignParams.roleId = this.checkedCities;
      console.log(this.assignParams);
      try {
        let res = await asyncDoAssign(this.assignParams);
        // console.log(res);
        this.isShowSetUser = false;
        this.getUserList();
      } catch (error) {
        console.log(error);
      }
    },
    //删除用户管理的回调
    async removeUser(row) {
      this.$confirm(`是否删除${row.username}?`, "确认删除", {})
        .then(async () => {
          try {
            let res = await asyncDeleteUser(row.id);
            // console.log(res);
            this.getUserList();
            this.$message({
              type: "success",
              message: "删除成功",
            });
          } catch (error) {
            console.log(error);
          }
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "取消删除",
          });
        });
    },
    // 点击单个表格选中框的回调
    checkedTable(row) {
      // console.log(row);
      this.idList = row.map((item) => item.id);
    },
    // 点击表格全选的回调
    async checkAllTable(row) {
      this.idList = row.map((item) => item.id);
      // console.log(this.idList);
    },
    // 点击批量删除的回调
    async removeUserList() {
      try {
        let res = await asyncDeleteUserList(this.idList);
        console.log(res);
        this.getUserList();
      } catch (error) {
        console.log(error);
      }
    },
  },
  mounted() {
    this.getUserList();
  },
};
</script>

<style>
</style>